<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta charset="utf-8"/>
    <title>首页</title>
</head>
<body>
<div id="title">

</div>
<!-- js部分 -->
<script type="text/javascript" th:src="@{/js/jquery/jquery-3.2.1.min.js}"></script>
<script type="text/javascript" th:src="@{/js/Math.uuid.js}"></script>
<script>
    openWebSocket();
    function openWebSocket(){
        var ws;
        if ("WebSocket" in window) {
            //如果已经有连接，则断开并重新连接
            if (ws != null) {
                ws.close();
                ws = null;
            }
            // 创建一个 websocket
            ws = new WebSocket(document.location.href.replace("https", "ws").replace("http", "ws") + "webSocket/" + getKey());
            ws.onopen = function () {
                console.log('WebSocket1连接已建立')
            };
            //获得消息事件
            ws.onmessage = function (evt) {
                var flag = isJSON(evt.data);
                if(flag){
                    var json = JSON.parse(evt.data);
                    console.log("消息数："+json.size+"::::"+json.msg);
                    var msgList = json.msg;
                    msgList.forEach(function(e){
                        $("#title").append('<p>'+e+'</p>');
                    });
                }else{
                    console.log(evt.data)
                    $("#title").append('<p>'+evt.data+'</p>');
                }

            };
            ws.onclose = function () {
                console.log('WebSocket1连接已断开')
            };
        } else {
            // 浏览器不支持 WebSocket
            console.log('您的浏览器不支持 WebSocket!');
        }
    }

    function getKey(){
        var value = window.sessionStorage.getItem('id');
        if(value==null || value== "" || value == undefined){
            value = Math.uuid();
            window.sessionStorage.setItem('id', value);
        }
        return value;

    }

    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }
            } catch(e) {
                return false;
            }
        }
    }
</script>
</body>
</html>
